package impl

import (
	"context"

	"gitee.com/go-course/go11/devcloud-mini/mcenter/apps/role"
	"gitee.com/go-course/go11/devcloud-mini/mcenter/apps/user"
	"github.com/infraboard/mcube/validator"
	"go.mongodb.org/mongo-driver/bson"
)

// 创建用户
func (i *impl) CreateUser(ctx context.Context, in *user.CreateUserRequest) (
	*user.User, error) {
	if err := validator.Validate(in); err != nil {
		return nil, err
	}

	ins := user.NewUser(in)

	_, err := i.col.InsertOne(ctx, ins)
	if err != nil {
		return nil, err
	}
	return ins, nil
}

// 查询用户
func (i *impl) DescribeUser(ctx context.Context, in *user.DescribeUserRequest) (
	*user.User, error) {
	// 2
	res := i.col.FindOne(ctx, bson.M{"username": in.Name})
	ins := user.NewUser(user.NewCreateUserRequest())
	err := res.Decode(ins)
	if err != nil {
		return nil, err
	}

	// 查询用户管理的角色 3
	if ins.Spec.RoleIds != nil && len(ins.Spec.RoleIds) > 0 {
		rs, err := i.role.QueryRole(ctx, &role.QueryRoleRequest{RoleIds: ins.Spec.RoleIds})
		if err != nil {
			return nil, err
		}
		ins.Roles = rs
	}
	return ins, nil
}
